package com.luojing.myThread.semaphore;

import java.util.concurrent.Semaphore;

/**
 * @author luojing
 * @create 2018/08/25 上午11:13 信号量,排队场景,放一部分人,然后在放一对人
 **/
public class SemaphoreDemo {

  public static void main(String[] args) {
    final Semaphore semaphore = new Semaphore(3);
    for (int i = 1; i <= 10; i++) {
      new Thread(new UserPlay("我是用户" + i, (i * 1000), semaphore)).start();
    }
    System.out.println("game over");
  }

  static class UserPlay implements Runnable {

    private String userName;

    private long playTime;

    private Semaphore semaphore;

    public UserPlay(String userName, long playTime, Semaphore semaphore) {
      this.userName = userName;
      this.playTime = playTime;
      this.semaphore = semaphore;
    }

    @Override
    public void run() {
      try {
        System.out.println("user:" + userName + "来玩了");
        Thread.sleep(2000);
        semaphore.acquire();
        System.out.println("user:" + userName + "开始玩耍了");
        Thread.sleep(playTime);
        System.out.println("user:" + userName + "玩耍结束");
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        semaphore.release();
      }
    }
  }
}
